<template>
	<div>
		<div class="page-tool">
			<div class="page-tool-item" @click="lastPage">上一页</div>
			<div class="page-tool-item" @click="nextPage">下一页</div>
			<div class="page-tool-item">{{ state.pageNum }}/{{ state.numPages }}</div>
			<div class="page-tool-item" @click="pageZoomOut">放大</div>
			<div class="page-tool-item" @click="pageZoomIn">缩小</div>
		</div>
		<vue-pdf-embed ref='pdf' :source="state.source" :style="scale" :page="state.pageNum" class="vue-pdf-embed" />
	</div>
</template>
<script setup>
	//npm install vue-pdf-embed
	//npm install pdfjs-dist@2.0.943 
	//vue3.0版本跨域问题目前解决不了
	// 引入插件
	import {
		ref,
		reactive,
		onMounted,
		computed
	} from "vue";
	import VuePdfEmbed from 'vue-pdf-embed';
	import * as pdfjsLib from 'pdfjs-dist';
	//定义
	const state = reactive({
		source: '/aaaaa.pdf', // 预览pdf文件地址
		pageNum: 1, // 当前页面
		scale: 1, // 缩放比例
		numPages: 0 // 总页数
	})
	


	const scale = computed(() => `transform:scale(${state.scale})`)
	onMounted(() => {
		getPdfUrl(state.source) // pdfUrl即url地址链接
	})
	
	// 打开弹窗
	function commentClick(url) {
		getPdfUrl(url);
	};
	
	function getPdfUrl(data) {
		state.source = data
		pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.js'
		const loadingTask = pdfjsLib.getDocument(data)
		loadingTask.promise.then(pdf => {
			state.numPages = pdf.numPages
		})
	}
	// 上一页
	function lastPage() {
		if (state.pageNum > 1) {
			state.pageNum -= 1
		}
	}
	// 下一页
	function nextPage() {
		if (state.pageNum < state.numPages) {
			state.pageNum += 1
		}
	}
	// 放大
	function pageZoomOut() {
		if (state.scale < 2) {
			state.scale += 0.1
		}
	}
	// 缩小
	function pageZoomIn() {
		if (state.scale > 1) {
			state.scale -= 0.1
		}
	}
	
	//将属性或者函数暴露给父组件
	defineExpose({ commentClick });
</script>
<style lang="scss" scoped>
	.page-tool {
		display: flex;
		position: absolute;
		// top: 5px;
		left: 83%;
		z-index: 100;
		transform: translateX(-50%);
		align-items: center;
		background: rgb(66 66 66);
		color: white;
		border-radius: 19px;
		cursor: pointer;
		justify-content: center;
		font-size: 15px;
	}

	.page-tool-item {
		padding: 4px 10px;
		cursor: pointer;
	}
</style>